/**
 * Copyright (c) 2018-2028, Chill Zhuang 庄骞 (smallchill@163.com).
 * <p>
 * Licensed under the GNU LESSER GENERAL PUBLIC LICENSE 3.0;
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.gnu.org/licenses/lgpl.html
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.springblade.modules.bank.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.AllArgsConstructor;
import org.springblade.core.boot.ctrl.BladeController;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.Func;
import org.springblade.modules.bank.entity.TmCustomerCallRecord;
import org.springblade.modules.bank.service.ITmCustomerCallRecordService;
import org.springblade.modules.bank.vo.TmCustomerCallRecordVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.*;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

/**
 * 客户呼叫记录 控制器
 *
 * @author Blade
 * @since 2022-07-08
 */
@RestController
@RequestMapping
@Api(value = "客户呼叫记录", tags = "客户呼叫记录接口")
public class RecordController extends BladeController {

	@Autowired
	private ITmCustomerCallRecordService tmCustomerCallRecordService;

	@Value("${recordFilePath}")
	private String recordFilePath;

	/**
	 * 文件上传具体实现方法;
	 *
	 * @param file
	 * @return
	 */
	@PostMapping("/upload")
	@ResponseBody
	@Transactional(rollbackFor = Exception.class)
	public String handleFileUpload(MultipartFile file) {
		if (!file.isEmpty()) {
			try {
				/*
				 * 这段代码执行完毕之后，图片上传到了工程的跟路径； 大家自己扩散下思维，如果我们想把图片上传到
				 * d:/files大家是否能实现呢？ 等等;
				 * 这里只是简单一个例子,请自行参考，融入到实际中可能需要大家自己做一些思考，比如： 1、文件路径； 2、文件名；
				 * 3、文件格式; 4、文件大小的限制;
				 */

				DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
				String today = LocalDate.now().format(dtf);
				File pathTemp = new File(recordFilePath + "/" + today  + "/");
				if(!pathTemp.exists()){
					pathTemp.mkdirs();
				}

				String filePath = today + "/" +file.getOriginalFilename();

				System.out.println(file.getSize());
				System.out.println(file.getOriginalFilename());
				System.out.println(file.getBytes());
				System.out.println(file.getContentType());

				//更新录音文件记录信息
				String updateSql = "update tm_customer_call_record t \n" +
					"set t.file_path='"+filePath+"',t.file_size="+file.getSize()+",t.file_type='"+file.getContentType()+"',t.upload_time=SYSDATE()\n" +
					"where t.file_name='"+file.getOriginalFilename()+"'";
				tmCustomerCallRecordService.updateBySql(updateSql);

				BufferedOutputStream out = new BufferedOutputStream(
					new FileOutputStream(new File(recordFilePath+"/"+filePath)));
				System.out.println(file.getName());
				out.write(file.getBytes());
				out.flush();
				out.close();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
				JSONObject retJSON = new JSONObject();
				retJSON.put("msg","ok");
				retJSON.put("code",200);
				return retJSON.toJSONString();
			} catch (IOException e) {
				e.printStackTrace();
				JSONObject retJSON = new JSONObject();
				retJSON.put("msg","ok");
				retJSON.put("code",200);
				return retJSON.toJSONString();
			}

			JSONObject retJSON = new JSONObject();
			retJSON.put("msg","ok");
			retJSON.put("code",200);
			return retJSON.toJSONString();

		} else {
			JSONObject retJSON = new JSONObject();
			retJSON.put("msg","ok");
			retJSON.put("code",200);
			return retJSON.toJSONString();
		}
	}

	@RequestMapping("/getFile")
	@ApiOperationSupport(order = 4)
	public void getImg(@ApiIgnore @RequestParam("fileName") String fileName, @ApiIgnore @RequestParam("filePath") String filePath, HttpServletRequest request, HttpServletResponse response) throws Exception {
		File file = new File(recordFilePath+"/"+filePath);

		//下载文件,使用spring框架中的FileCopyUtils工具
		String extendFileName = fileName.substring(0,fileName.lastIndexOf('.'));
		//动态设置响应类型，根据前台传递文件类型设置响应类型
		response.setContentType(request.getSession().getServletContext().getMimeType(extendFileName));
		//设置响应头,attachment表示以附件的形式下载，inline表示在线打开
		if(   fileName.toLowerCase().indexOf("jpeg")>0 || fileName.toLowerCase().indexOf("jpg")>0 || fileName.toLowerCase().indexOf("png")>0 || fileName.toLowerCase().indexOf("pdf")>0){
			response.setHeader("content-disposition","inline;fileName="+ URLEncoder.encode(fileName,"UTF-8"));
		}else{
			response.setHeader("content-disposition","attachment;fileName="+ URLEncoder.encode(fileName,"UTF-8"));
		}
		//获取输出流对象（用于写文件）
		ServletOutputStream os = response.getOutputStream();
		//下载文件,使用spring框架中的FileCopyUtils工具

		FileCopyUtils.copy(FileCopyUtils.copyToByteArray(file),os);
	}

	/**
	 * 文件上传具体实现方法;
	 *
	 * @param file
	 * @return
	 */
	@PostMapping("/upload2")
	@ResponseBody
	public String handleFileUpload2(@RequestParam("file") MultipartFile file) {
		if (!file.isEmpty()) {
			try {
				/*
				 * 这段代码执行完毕之后，图片上传到了工程的跟路径； 大家自己扩散下思维，如果我们想把图片上传到
				 * d:/files大家是否能实现呢？ 等等;
				 * 这里只是简单一个例子,请自行参考，融入到实际中可能需要大家自己做一些思考，比如： 1、文件路径； 2、文件名；
				 * 3、文件格式; 4、文件大小的限制;
				 */
				BufferedOutputStream out = new BufferedOutputStream(
					new FileOutputStream(new File(
						file.getOriginalFilename())));
				System.out.println(file.getName());
				out.write(file.getBytes());
				out.flush();
				out.close();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
				return "上传失败," + e.getMessage();
			} catch (IOException e) {
				e.printStackTrace();
				return "上传失败," + e.getMessage();
			}

			return "上传成功";

		} else {
			return "上传失败，因为文件是空的.";
		}
	}

}
